<template>
  <admin-layout>
    <div class="merchants-view">
      <h2 class="page-title">商家管理</h2>

      <!-- 搜索区域 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="店铺名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入店铺名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="店主">
            <el-input
              v-model="searchForm.ownerName"
              placeholder="请输入店主姓名"
              clearable
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 商家列表 -->
      <el-card class="table-card" v-loading="loading">
        <el-table :data="merchantList" border style="width: 100%" row-key="id">
          <el-table-column label="店铺Logo" width="80" align="center">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.logo">
                {{ row.name?.substring(0, 1) }}
              </el-avatar>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="店铺名称" min-width="120" />

          <el-table-column prop="ownerName" label="店主" min-width="100" />

          <el-table-column prop="phone" label="联系电话" min-width="120" />

          <el-table-column prop="address" label="店铺地址" min-width="180" />

          <el-table-column prop="category" label="分类" width="100" />

          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.status === 'PENDING'
                    ? 'warning'
                    : row.status === 'APPROVED' // 将 OPEN 替换为 APPROVED
                    ? 'success'
                    : row.status === 'OPEN' // 如果后端仍返回 OPEN，也显示为 success
                    ? 'success'
                    : row.status === 'SUSPENDED'
                    ? 'danger'
                    : 'info'
                "
              >
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" min-width="160">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="220" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'PENDING'"
                size="small"
                type="success"
                @click="handleReview(row, 'approve')"
              >
                通过
              </el-button>
              <el-button
                v-if="row.status === 'PENDING'"
                size="small"
                type="danger"
                @click="handleReview(row, 'reject')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="row.status === 'SUSPENDED'"
                size="small"
                type="success"
                @click="handleStatusChange(row, 'OPEN')"
              >
                启用店铺
              </el-button>
              <el-button
                size="small"
                type="primary"
                @click="viewMerchantDetail(row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="merchantList.length === 0 && !loading" class="empty-data">
          暂无商家数据
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="pagination.total > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :page-size="pagination.pageSize"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>

      <!-- 审核对话框 -->
      <el-dialog
        v-model="reviewDialog.visible"
        :title="reviewDialog.title"
        width="500px"
      >
        <el-form :model="reviewForm" label-width="80px">
          <el-form-item label="审核结果">
            <el-radio-group v-model="reviewForm.status">
              <el-radio label="APPROVED">通过</el-radio>
              <el-radio label="SUSPENDED">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="审核理由"
            v-if="reviewForm.status === 'SUSPENDED'"
          >
            <el-input
              v-model="reviewForm.reason"
              type="textarea"
              rows="3"
              placeholder="请输入拒绝理由"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="reviewDialog.visible = false">取消</el-button>
            <el-button
              type="primary"
              @click="submitReview"
              :loading="reviewDialog.loading"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 商家详情对话框 -->
      <el-dialog
        v-model="detailDialog.visible"
        title="商家详情"
        width="700px"
        class="merchant-detail-dialog"
      >
        <div class="merchant-detail" v-if="detailDialog.merchant">
          <div class="merchant-header">
            <el-avatar
              :size="60"
              :src="detailDialog.merchant.logo"
              class="merchant-logo"
            >
              {{ detailDialog.merchant.name?.substring(0, 1) }}
            </el-avatar>
            <div class="merchant-title">
              <h3>{{ detailDialog.merchant.name }}</h3>
              <div>
                <el-tag
                  :type="
                    detailDialog.merchant.status === 'PENDING'
                      ? 'warning'
                      : detailDialog.merchant.status === 'APPROVED' ||
                        detailDialog.merchant.status === 'OPEN'
                      ? 'success'
                      : detailDialog.merchant.status === 'SUSPENDED'
                      ? 'danger'
                      : 'info'
                  "
                >
                  {{ getStatusLabel(detailDialog.merchant.status) }}
                </el-tag>
              </div>
            </div>
          </div>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="店铺ID">
              {{ detailDialog.merchant.id }}
            </el-descriptions-item>
            <el-descriptions-item label="店主">
              {{ detailDialog.merchant.ownerName }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ detailDialog.merchant.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="分类">
              {{ detailDialog.merchant.category }}
            </el-descriptions-item>
            <el-descriptions-item label="地址" :span="2">
              {{ detailDialog.merchant.address }}
            </el-descriptions-item>
            <el-descriptions-item label="营业时间" :span="2">
              {{ detailDialog.merchant.businessHours || "未设置" }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" :span="2">
              {{ formatDate(detailDialog.merchant.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">
              {{ detailDialog.merchant.description || "暂无描述" }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="detail-actions">
            <el-button
              v-if="detailDialog.merchant.status === 'SUSPENDED'"
              type="success"
              @click="handleStatusChange(detailDialog.merchant, 'OPEN')"
            >
              启用店铺
            </el-button>
            <el-button
              v-if="
                detailDialog.merchant.status === 'OPEN' ||
                detailDialog.merchant.status === 'APPROVED'
              "
              type="danger"
              @click="handleStatusChange(detailDialog.merchant, 'SUSPENDED')"
            >
              禁用店铺
            </el-button>
            <el-button @click="detailDialog.visible = false">关闭</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </admin-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getMerchants, reviewStore } from "@/api";
import AdminLayout from "@/components/admin/AdminLayout.vue";

// 定义商家类型
interface Merchant {
  id: string;
  name: string;
  ownerName: string; // 店主名称
  userId: string; // 店主用户ID
  phone: string;
  address: string;
  category: string;
  categoryId?: string; // 分类ID
  description?: string;
  businessHours?: string;
  logo?: string;
  status: string;
  createTime: string;
}

// 商家列表
const merchantList = ref<Merchant[]>([]);

// 加载状态
const loading = ref(false);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 搜索参数
const searchForm = reactive({
  name: "",
  ownerName: "",
  status: "",
});

// 状态选项
const statusOptions = [
  { value: "PENDING", label: "待审核" },
  { value: "OPEN", label: "营业中" },
  { value: "APPROVED", label: "已通过" },
  { value: "CLOSED", label: "已关闭" },
  { value: "SUSPENDED", label: "已禁用" },
];

// 审核对话框
const reviewDialog = reactive({
  visible: false,
  title: "商家审核",
  loading: false,
  merchant: null as Merchant | null,
});

// 审核表单
const reviewForm = reactive({
  id: "",
  status: "APPROVED",
  reason: "",
});

// 详情对话框
const detailDialog = reactive({
  visible: false,
  merchant: null as Merchant | null,
});

// 获取商家列表
const fetchMerchants = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      name: searchForm.name || undefined,
      ownerName: searchForm.ownerName || undefined,
      status: searchForm.status || undefined,
    };

    console.log("正在请求商家数据，参数:", params);
    const res = await getMerchants(params);
    console.log("getMerchants API响应:", res);

    const data = res.data?.data || res.data;
    console.log("解析后的数据:", data);

    if (data) {
      // 使用API文档中定义的分页格式
      // 确保将API返回的数据正确映射到我们的Merchant接口
      merchantList.value = (data.content || []).map((item) => ({
        ...item,
        // 如果API返回的店主名称字段与我们的不一致，进行映射
        ownerName: item.ownerName || item.userName || "未知",
        // 其他字段映射...
        createTime: item.createdAt || item.createTime,
      }));
      pagination.total = data.totalElements || 0;
      console.log("成功获取商家数据:", merchantList.value);
    } else {
      console.warn("API返回数据为空或格式不正确");
      merchantList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取商家列表失败:", error);
    ElMessage.error("获取商家列表失败，请检查网络连接或API状态");
    merchantList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchMerchants();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  pagination.currentPage = 1;
  fetchMerchants();
};

// 处理页面变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchMerchants();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchMerchants();
};

// 获取状态标签
const getStatusLabel = (status: string): string => {
  const statusMap: Record<string, string> = {
    PENDING: "待审核",
    OPEN: "营业中",
    APPROVED: "已通过", // 添加 APPROVED 状态的标签
    CLOSED: "已关闭",
    SUSPENDED: "已禁用",
  };
  return statusMap[status] || status;
};

// 处理审核
const handleReview = (merchant: Merchant, status: string) => {
  reviewDialog.merchant = merchant;
  reviewDialog.visible = true;
  reviewForm.id = merchant.id;
  reviewForm.status = status === "approve" ? "APPROVED" : "SUSPENDED";
  reviewForm.reason = "";
};

// 提交审核
const submitReview = async () => {
  if (!reviewForm.id) return;

  reviewDialog.loading = true;
  try {
    await reviewStore(
      reviewForm.id,
      reviewForm.status,
      reviewForm.status === "SUSPENDED" ? reviewForm.reason : undefined
    );

    // 更新本地数据
    const index = merchantList.value.findIndex(
      (item) => item.id === reviewForm.id
    );
    if (index !== -1) {
      merchantList.value[index].status = reviewForm.status; // 直接使用审核结果的状态
    }

    ElMessage.success(
      `商家${reviewForm.status === "APPROVED" ? "审核通过" : "拒绝"}成功`
    );
    reviewDialog.visible = false;
  } catch (error) {
    console.error("审核操作失败", error);
    ElMessage.error("审核操作失败，请重试");
  } finally {
    reviewDialog.loading = false;
  }
};

// 查看商家详情
const viewMerchantDetail = (merchant: Merchant) => {
  detailDialog.merchant = merchant;
  detailDialog.visible = true;
};

// 格式化时间
const formatDate = (dateString: string): string => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 处理状态变更
const handleStatusChange = async (merchant: Merchant, targetStatus: string) => {
  const actionText = targetStatus === "OPEN" ? "启用" : "禁用";
  const apiStatus = targetStatus === "OPEN" ? "APPROVED" : "SUSPENDED"; // 根据API文档调整

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}店铺 ${merchant.name} 吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 调用审核API
    await reviewStore(
      merchant.id,
      apiStatus, // 使用调整后的API状态
      targetStatus === "SUSPENDED" ? "管理员禁用" : undefined
    );

    // 更新本地数据
    merchant.status = apiStatus; // 本地状态也更新为API发送的状态

    // 如果是在详情对话框中操作的，更新对话框中的数据
    if (detailDialog.merchant && detailDialog.merchant.id === merchant.id) {
      detailDialog.merchant.status = apiStatus;
    }

    ElMessage.success(`${actionText}店铺成功`);
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${actionText}店铺失败`, error);
      ElMessage.error(`${actionText}店铺失败，请重试`);
    }
  }
};

onMounted(() => {
  fetchMerchants();
});
</script>

<style scoped>
.merchants-view {
  width: 100%;
}

.page-title {
  margin-bottom: 20px;
  color: var(--primary-dark);
  font-size: 1.5rem;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  min-height: 400px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.merchant-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.merchant-logo {
  margin-right: 15px;
}

.merchant-title {
  display: flex;
  flex-direction: column;
}

.merchant-title h3 {
  margin: 0 0 10px 0;
  font-size: 1.2rem;
  color: var(--text-primary);
}

.merchant-detail-dialog .detail-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
